package com.kelvem.saas.workbanch.ontology.piaoorder.handle.create;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kelvem.saas.workbanch.fsm.core.EventContext;
import com.kelvem.saas.workbanch.fsm.entity.Entity;
import com.kelvem.saas.workbanch.fsm.handle.Handle;
import com.kelvem.saas.workbanch.ontology.piaoorder.dao.PiaoOrderDao;
import com.kelvem.saas.workbanch.ontology.piaoorder.model.PiaoOrderEntity;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * @author kelvem
 */
@Service
@Slf4j
public class CreatePiaoNoHandle extends Handle {
    
    // piaoOrderNo的缓存
    private static Set<String> piaoOrderNoSet;
    
    @Resource
    private PiaoOrderDao piaoOrderDao;
    
    @Override
    public void execute() {
    
        PiaoOrderEntity order = Entity.instance().selectOne(PiaoOrderEntity.class);
        
        order.setPiaoOrderNo(this.createOrderNo());
        
        log.info("Handle[" + getName() + "] order=" + order);
        EventContext.print();
    }
    
    public String createOrderNo() {
        
        Date now = new Date();
        DateFormat format = new SimpleDateFormat("yyMMdd");
        String strNow = format.format(now);
        log.info("createOrderNo, now=" + strNow);
        
        if (piaoOrderNoSet == null) {
            synchronized (this) {
                if (piaoOrderNoSet == null) {
                    LambdaQueryWrapper<PiaoOrderEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.gt(PiaoOrderEntity::getPiaoOrderNo, strNow);
                    List<PiaoOrderEntity> piaoOrderList = piaoOrderDao.selectList(lambdaQueryWrapper);
                    
                    piaoOrderNoSet = new HashSet<>();
                    for (PiaoOrderEntity order :
                            piaoOrderList) {
                        piaoOrderNoSet.add(order.getPiaoOrderNo());
                    }
                }
            }
        }
        
        String orderNo;
        do {
            int index = (int)(new Random().nextDouble() * 100) + 10000;
            orderNo = strNow + "-" + index;
            log.info("createOrderNo, create=" + orderNo);
        } while (piaoOrderNoSet.contains(orderNo) == true);
        
        piaoOrderNoSet.add(orderNo);
        
        log.info("createOrderNo, orderNo=" + orderNo);
        
        return orderNo;
    }
    
}
